import sys, re
import urllib2

class SearchFor:

    def __init__(self, name, regex, page, type):
        """ Data class to organize searching for lolking

        Args:
             name: The type of data being displayed, ie ELO
             regex: the expression to locate this type of data
             page: the page of the lolking file to parse, ie profile/ranked-stats
             type: the printing format type (integeger) see getData
        Returns: None
        """
        self.regex = regex
        self.page = page
        self.name = name
        self.type = type


class LolStocker:

    def __init__(self, name, region):
        """ Scrapes data from lolking.net

        Args:
             name: Summoner name (case sensitive)
             region: Server name, ie NA
        Class Vars:
            self.name: Summoner name
            self.html: Html page response from looking reading self.url
            self.region: Server name
            self.updateURL: Boolean to see if we have to reping the website
            self.url: Current url to ping for information
            self.DEBUG: Boolean to see if in debug mode
            self.BASE_URL: Constant initial part of a lolking search
            self.data: Array of SearchFor objects
            self.page: The current page of a Summoner's profile
        Returns:
            None
        """
        self.name = name
        self.region = region
        self.data = []
        self.BASE_URL = 'http://www.lolking.net/search?'
        self.page = ''
        self.html = ''
        self.url = ''
        self.createSearch('Game Mode   ', re.compile(re.escape('<div class="personal_ratings_heading">') + '([^<]+)' + re.escape('</div>')), 'profile', 1)
        self.createSearch('ELO         ', re.escape('0px;">') + '(\\d+)', 'profile', 1)
        self.createSearch('League      ', '\\;\\"\\>([a-zA-Z ]+)\\s?\\<span', 'profile', 1)
        self.createSearch('Division    ', '>([IV]+)</span></div>', 'profile', 1)
        self.createSearch('Ranked Stats', re.escape('<div style="display: table-cell; vertical-align: middle; padding-top: 3px"><a href=') + '[^>]+>(\\w+).*\\n.*\\n.*data-sortval="\\d+">(\\d+)</td>\\n.*data-sortval="\\d+">(\\d+)</td>\\n.*data-sortval="\\d+.?\\d*">(\\d+.?\\d*%)</td>', 'ranked-stats', 2)
        if len(sys.argv) > 1 and sys.argv[1] == 1:
            self.DEBUG = True
        else:
            self.DEBUG = False

    def createSearch(self, name, regex, page, type):
        """ Helper function to add a search to the data array
        """
        self.data.append(SearchFor(name, regex, page, type))

    def updateURL(self, page):
        """ Helper function to update the url based on what page the information is on
        """
        self.url = '{0}name={1}&region={2}#{3}'.format(self.BASE_URL, self.name, self.region, page)
        if self.DEBUG:
            print self.url

    def findData(self, searchFor):
        """ Sends a request to lolking and fetces data based on a SearchFor object

        Args:
             searchFor: The search criteria
        Returns:
            Array of matches based on searchFor's regex
        """
        self.updateURL(searchFor.page)
        words = []
        
        #update html only if it is a new page
        if searchFor.page != self.page:
            try:
                self.html = urllib2.urlopen(self.url).read()
                self.page = searchFor.page
            except:
                if self.DEBUG:
                    print 'ERROR: to open url {0}\t using text file'.format(self.url)

        words = re.findall(searchFor.regex, self.html)
        if self.DEBUG:
            print words
        return words

def compMostPalyed(a, b):
    """ Sorts champions based on most played games
    """
    return int(a[1]) + int(a[2]) - (int(b[1]) + int(b[2]))


def getData(searchFor, summoner):
    """ Prints data to the console based on the search criteria

    Args:
        searchFor: SearchFor object
        summoner: Summoner object
    Returns:
        None
    """
    array = summoner.findData(searchFor)
    if len(array) >= 1 and searchFor.type == 1:
        print 'Summoner {0}:\t {1}'.format(searchFor.name, array)
    elif len(array) >= 1 and searchFor.type == 2:
        array = sorted(array, cmp=compMostPalyed, reverse=True)
        print 'Summoner {0}:\nChamp\t    Wins\tLosses\tPercent'.format(searchFor.name)
        for i in range(0, 10):
            print '{0: <12}{1: <5}\t{2: <5}\t{3: <1}'.format(array[i][0], array[i][1], array[i][2], array[i][3])

    else:
        print 'Whoops could not find {0}'.format(searchFor.name)


def init():
    """ Runs the script
    """
    name = ''
    regoin = ''
    
    #populate summoner name and region
    if len(sys.argv) == 3:
        name = sys.argv[1]
        region = sys.argv[2]
    else:
        name = raw_input('Please enter summoners name: ')
        region = raw_input('Please enter summoners region: ')
    
    summoner = LolStocker(name, region)
    print 'Summoner name: {0}\t Region: {1}'.format(summoner.name, summoner.region)
    
    #print the summoner's data
    for at in summoner.data:
        getData(at, summoner)



print 'Welcome to LOL Stocker'
init()
